package com.lee.study.thrift.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import org.apache.thrift.protocol.TMessageType;
import org.apache.thrift.protocol.TType;

public class ThriftResponse extends ChannelInboundHandlerAdapter {

    protected static final int VERSION_MASK = 0xffff0000;
    protected static final int VERSION_1 = 0x80010000;


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        super.channelRead(ctx, msg);
    }

    private void response(ChannelHandlerContext ctx) {
        ByteBuf byteBuf = ctx.alloc().buffer();
        //写TMessage
        int version = VERSION_1 | TMessageType.REPLY;
        byteBuf.writeInt(version);
        byte[] nameBytes = "say".getBytes(CharsetUtil.UTF_8);
        byteBuf.writeInt(nameBytes.length);
        byteBuf.writeBytes(nameBytes);
        byteBuf.writeInt(1);
        //写返回值
        byteBuf.writeByte(TType.I32); //type
        byteBuf.writeShort(0); //id
        byteBuf.writeInt(888);
        byteBuf.writeByte(TType.STOP);

//        byte[] array = byteBuf.array();
//        int len = array.length;

        //int size = byteBuf.writerIndex();

//        ctx.write(size);
//        ctx.write(byteBuf);


        int len = byteBuf.readableBytes();
        byte[] data = new byte[len];
        byteBuf.getBytes(byteBuf.readerIndex(), data);


//        CompositeByteBuf response = ctx.alloc().compositeBuffer()
//                .addComponent(ctx.alloc().buffer().writeInt(len))
//                .addComponent(byteBuf);
//        ctx.write(ctx.alloc().buffer().writeInt(len));
//        ctx.write(byteBuf);

        ctx.write(len);
        ctx.write(data);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        super.channelReadComplete(ctx);
    }
}
